package com.rabbiter.fm.controller;

import com.rabbiter.fm.common.utils.PathUtils;
import com.rabbiter.fm.service.FileService;
import com.rabbiter.fm.common.enums.ErrorMsg;
import com.rabbiter.fm.common.utils.IdFactoryUtil;
import com.rabbiter.fm.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@CrossOrigin
@RestController
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 上传文件
     */
    @PostMapping("/file")
    public ResultVo uploadFile(@RequestParam("file") MultipartFile multipartFile) {
        String uuid = "file" + IdFactoryUtil.getFileId();
        String fileName = uuid + multipartFile.getOriginalFilename();
        try {
            if (fileService.uploadFile(multipartFile, fileName)) {
                return ResultVo.success("/image?imageName=" + fileName);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            return ResultVo.fail(ErrorMsg.SYSTEM_ERROR);
        }
        return ResultVo.fail(ErrorMsg.FILE_UPLOAD_ERROR);
    }

    /**
     * 获取图片或视频资源
     */
    @GetMapping("/image")
    public void getImage(@RequestParam("imageName") String imageName,
                         HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        // 构造文件路径
        File fileDir = new File(PathUtils.getClassLoadRootPath() + "/pic");
        File image = new File(fileDir.getAbsolutePath() + "/" + imageName);

        if (!image.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 文件不存在时返回 404
            return;
        }

        long fileLength = image.length();
        long start = 0; // 起始字节位置
        long end = fileLength - 1; // 结束字节位置

        // 处理 Range 请求（分块传输）
        String rangeHeader = request.getHeader(HttpHeaders.RANGE);
        if (rangeHeader != null && rangeHeader.startsWith("bytes=")) {
            String[] ranges = rangeHeader.substring("bytes=".length()).split("-");
            start = Long.parseLong(ranges[0]);
            if (ranges.length > 1 && !ranges[1].isEmpty()) {
                end = Long.parseLong(ranges[1]);
            }
        }

        // 设置响应头
        response.setContentType(getContentType(imageName));
        response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");

        if (rangeHeader != null) {
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 返回 206 Partial Content
            response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + start + "-" + end + "/" + fileLength);
            response.setContentLength((int) (end - start + 1));
        } else {
            response.setContentLength((int) fileLength);
        }

        // 读取文件并写入响应输出流
        try (FileInputStream fileInputStream = new FileInputStream(image);
             OutputStream outputStream = response.getOutputStream()) {
            fileInputStream.skip(start); // 跳过指定字节
            byte[] buffer = new byte[1024];
            int bytesRead;
            long remaining = end - start + 1;
            while (remaining > 0 && (bytesRead = fileInputStream.read(buffer, 0, (int) Math.min(buffer.length, remaining))) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                remaining -= bytesRead;
            }
        }
    }

    /**
     * 根据文件名动态获取 Content-Type
     */
    private String getContentType(String fileName) {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "mp4":
                return "video/mp4";
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            default:
                return "application/octet-stream"; // 默认类型（可能会触发下载）
        }
    }
}

//package com.rabbiter.fm.controller;
//
//import com.rabbiter.fm.common.utils.PathUtils;
//import com.rabbiter.fm.service.FileService;
//import com.rabbiter.fm.common.enums.ErrorMsg;
//import com.rabbiter.fm.common.utils.IdFactoryUtil;
//import com.rabbiter.fm.vo.ResultVo;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.web.bind.annotation.*;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.File;
//import java.io.FileInputStream;
//import java.io.IOException;
//import java.io.OutputStream;
//@CrossOrigin
//@RestController
//public class FileController {
//
//    @Autowired
//    private FileService fileService;
//
//    @PostMapping("/file")
//    public ResultVo uploadFile(@RequestParam("file") MultipartFile multipartFile) {
//        String uuid="file"+ IdFactoryUtil.getFileId();
//        String fileName= uuid+ multipartFile.getOriginalFilename();
//        try {
//            if (fileService.uploadFile(multipartFile,fileName)) {
//                return ResultVo.success("/image?imageName="+fileName);
//            }
//        } catch (IOException e) {
//            System.out.println(e.getMessage());
//            return ResultVo.fail(ErrorMsg.SYSTEM_ERROR);
//        }
//        return ResultVo.fail(ErrorMsg.FILE_UPLOAD_ERROR);
//    }
//
//    @GetMapping("/image")
//    public void getImage(@RequestParam("imageName") String imageName,
//                         HttpServletResponse response) throws IOException {
//        // 构造文件路径
//        File fileDir = new File(PathUtils.getClassLoadRootPath() + "/pic");
//        File image = new File(fileDir.getAbsolutePath() + "/" + imageName);
//
//        if (image.exists()) {
//            // 设置响应头
//            response.setContentType(getContentType(imageName)); // 动态设置 Content-Type
//            response.setContentLength((int) image.length()); // 设置文件大小
//
//            // 读取文件并写入响应输出流
//            try (FileInputStream fileInputStream = new FileInputStream(image);
//                 OutputStream outputStream = response.getOutputStream()) {
//                byte[] buffer = new byte[1024];
//                int bytesRead;
//                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, bytesRead);
//                }
//            }
//        } else {
//            response.setStatus(HttpServletResponse.SC_NOT_FOUND); // 文件不存在时返回 404
//        }
//    }
//
//    /**
//     * 根据文件名动态获取 Content-Type
//     */
//    private String getContentType(String fileName) {
//        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
//        switch (extension) {
//            case "mp4":
//                return "video/mp4";
//            case "jpg":
//            case "jpeg":
//                return "image/jpeg";
//            case "png":
//                return "image/png";
//            case "gif":
//                return "image/gif";
//            default:
//                return "application/octet-stream"; // 默认类型（可能会触发下载）
//        }
//    }
//
//}
